package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    private final ApArticleMapper apArticleMapper;

    private final ApArticleConfigMapper apArticleConfigMapper;

    private final ApArticleContentMapper apArticleContentMapper;

    private final ArticleFreemarkerService articleFreemarkerService;

    private final CacheService cacheService;


    private final static short Max_Page_Size = 50;


    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param mess
     * @Author huangjianfei
     * @Version day11
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        Integer score = calculateScore(apArticle);
        score = score * 3;
        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }


    /**
     * 替换数据并且存入到redis
     *
     * @param apArticle
     * @param score
     * @param redisKey
     * @Author huangjianfei
     * @Version day11
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String redisKey) {
        String articleListStr = cacheService.get(redisKey);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);
            boolean flag = true;
            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }
            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }

                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(redisKey, JSON.toJSONString(hotArticleVoList));

        }
    }


    /**
     * 更新文章的阅读、点赞、收藏、评论的数量
     *
     * @param mess
     * @return
     * @Author huangjianfei
     * @Version day11
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = apArticleMapper.selectArticleById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection() == null ? 0 : apArticle.getCollection() + mess.getCollect());
        apArticle.setComment(apArticle.getComment() == null ? 0 : apArticle.getComment() + mess.getComment());
        apArticle.setLikes(apArticle.getLikes() == null ? 0 : apArticle.getLikes() + mess.getLike());
        apArticle.setViews(apArticle.getViews() == null ? 0 : apArticle.getViews() + mess.getView());
        apArticleMapper.updateArticleBehaviorData(apArticle);
        return apArticle;
    }

    /**
     * 更新文章的浏览数
     *
     * @param map
     */
    @Override
    public void updateArticleViewsCountToDb(Map map) {
        String articleIdStr = (String) map.get("articleId");
        Long articleId = Long.parseLong(articleIdStr);

        Integer views = (Integer) map.get("views");
        apArticleMapper.updateArticleViewsCount(articleId, views);
    }

    /**
     * 更新文章的点赞数到redis
     *
     * @param map
     * @return
     */
    @Override
    public void updateArticleLikesCountToRedis(Map map) {
        Long articleId = (Long) map.get("articleId");
        String likesCountKey = BehaviorConstants.ARTICLE_LIKE_COUNT;
        log.info("更新文章的点赞数到redis：文章id{}", articleId);
        Integer count = apArticleMapper.selectLikeCount(articleId);
        if (count == null) {
            count = 0;
        }
        cacheService.hPut(likesCountKey, articleId.toString(), count.toString());
    }

    /**
     * 更新文章的点赞数-接收kafka的消息
     *
     * @param map
     */
    @Override
    public void updateArticleLikesCountToDb(Map map) {
        Long articleId = (Long) map.get("articleId");
        Integer likeAction = (Integer) map.get("likeAction");
        ApArticle apArticle = apArticleMapper.selectOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, articleId));
        if (apArticle.getLikes() == null) {
            apArticle.setLikes(0);
        }
        if (likeAction == 0) {
            apArticle.setLikes(apArticle.getLikes() + 1);
        } else {
            apArticle.setLikes(apArticle.getLikes() - 1);
        }
        apArticleMapper.updateById(apArticle);
    }

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type 1 更多 2 最新
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {
        //1.校验参数
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        // 文章数量不超过50
        size = Math.min(size, Max_Page_Size);

        // 类型参数校验
        if (!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        // 频道校验
        if (StringUtils.isBlank(dto.getTag())) dto.setTag(ArticleConstants.DEFAULT_TAG);
        // 时间校验
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());

        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, type);
        return ResponseResult.okResult(articleList);
    }


    /**
     * 加载文章列表
     *
     * @param dto
     * @param type      1 更多 2 最新
     * @param firstPage true 首页，false 不是首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if (firstPage) {
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(jsonStr)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(dto, type);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {

/*        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/

        // 1、检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        // 2、判断是否存在id
        if (dto.getId() == null) {
            // 2.1、不存在id 保存 文章 文章配置 文章内容
            // 保存文章
            apArticleMapper.insert(apArticle);

            //保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            // 保存内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        } else {
            // 2.2 存在id 修改 文章 文章内容
            // 修改文章
            apArticleMapper.updateById(apArticle);

            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        //  异步调用，上传到minio，保存url
        articleFreemarkerService.buildArticleToMinIo(apArticle, dto.getContent());

        // 3、结果返回 文章id
        return ResponseResult.okResult(apArticle.getId());
    }


    /**
     * 计算单给文章分数
     *
     * @param apArticle
     * @return
     */
    private Integer calculateScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
